package org.hope.lee.producer;

import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendCallback;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.common.message.MessageQueue;
import com.alibaba.rocketmq.remoting.exception.RemotingException;

public class Producer {
	public static void main(String[] args) {
		DefaultMQProducer producer = new DefaultMQProducer("push_consumer");
//		producer.setNamesrvAddr("192.168.31.176:9876");
		producer.setNamesrvAddr("192.168.31.176:9876;192.168.31.165:9876");
		try {
			// 设置实例名称
			producer.setInstanceName("quick_start_producer");
			// 设置重试次数,默认2
			producer.setRetryTimesWhenSendFailed(3);
			//设置发送超时时间，默认是3000
			producer.setSendMsgTimeout(6000);
			//发送消息到多大时候进行压缩
			producer.setCompressMsgBodyOverHowmuch(1024*1024*10);
			//给broker发送心跳
			producer.setHeartbeatBrokerInterval(100);
			// 开启生产者
			producer.start();
			// 创建一条消息
			Message msg = new Message("PushTopic_tt1", "TagB", "OrderID0034", "uniform_just_for_test".getBytes());
			//目前发现3.2.6版本没有这个方法，3.5.3版本有这个方法，并且必须要设置为false否则会报错
//			producer.setVipChannelEnabled(false);
			SendResult send = producer.send(msg);
			System.out.println("id:--->" + send.getMsgId() + ",result:--->" + send.getSendStatus());
			//发送，并触发回调函数
			/*producer.send(msg, new SendCallback(){
				//成功回调函数
				@Override
				public void onSuccess(SendResult sendResult) {
					System.out.println(sendResult.getSendStatus());
					System.out.println("成功");
				}
				//异常回调函数
				@Override
				public void onException(Throwable e) {
					System.out.println("失败了" +  e.getMessage());
				}
			});*/
			
			//获取某个主题的消息队列  
            /*List<MessageQueue> messageQueues = producer  
                    .fetchPublishMessageQueues("PushTopic");  
            System.out.println(messageQueues.size());  */
            
			
		} catch (MQClientException e) {
			e.printStackTrace();
		} catch (RemotingException e) {
			e.printStackTrace();
		} catch (MQBrokerException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		producer.shutdown();
	}
}
